﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace KZ400B
{
    public partial class AxleManager
    {
        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="axleName"></param>
        /// <returns></returns>
        public static bool ToZero(string axleName,double period)
        {
            if (!IsOpen)
            {
                return false;
            }
            if (AxleCacheManager.AxleList[axleName] != null)
            {
                if (AxleCacheManager.AxleList[axleName].AxleActionStatus.VZeroIsSeted)
                {
                    setState(
                string.Format("[{0}] 轴 设置归零位命令:虚拟零位已经设定"
                        , axleName
                        ));
                    return true;
                }
            }
            //bool rst = false;
            string data = Protocol.Packet(
                Protocol.GetToZeroString(axleName,period)
                );
            return sendData(data);
            //try
            //{
            //    string msg = string.Empty;
            //    lock (s_spLocker)
            //    {
            //        //if (spLink.CanWrite)
            //        {
            //            spLink.Write(data);
            //            msg = spLink.ReadString();
            //            rst = handleNrmAck(FunctionCode.FCodeToZero,axleName,msg,false)
            //                == CommResultCode.Success
            //                ;
            //        }
            //    }
                
            //    if (OnAxleActionResponse != null)
            //    {
            //        OnAxleActionResponse(axleName
            //            , AxleCacheManager.getAxle(axleName)
            //            , AxleActions.ToZero
            //            , rst
            //            , string.Format("[{0}] 轴 归零命令响应 : {1} {2} "
            //            , axleName, rst.ToString(), rst ? "-> 归零运行中 ... " : string.Empty
            //            )
            //        );
            //    }
            //}
            //finally
            //{
            //    //setIsLocked(false);
            //}
            //return rst;
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="axleName"></param>
        /// <returns></returns>
        public static bool ToZeroIM(string axleName, double period)
        {
            if (AxleCacheManager.AxleList[axleName] != null)
            {
                if (AxleCacheManager.AxleList[axleName].AxleActionStatus.VZeroIsSeted)
                {
                    setState(
                string.Format("[{0}] 轴 设置归零位命令:虚拟零位已经设定"
                        , axleName
                        ));
                    return true;
                }
            }
            bool rst = ToZero(axleName, period);
            if (rst)
            {
                lock (s_spLocker)
                {
                    if (spLink.CanRead)
                    {
                        string msg = spLink.ReadString(10);
                        if (string.IsNullOrEmpty(msg))
                        {
                            return false;
                        }
                        ProtocolV2.UnpacketResult ur = ProtocolV2.Unpack(msg);
                        rst = ur.Result && ur.Action == AxleActions.ToZeroRespond;
                        if (!rst)
                        {
                            return rst;
                        }
                        OnToZeroRespond(ur);


                        msg = spLink.ReadString(240);
                        if (string.IsNullOrEmpty(msg))
                        {
                            return false;
                        }
                        ur = ProtocolV2.Unpack(msg);
                        rst = ur.Result && ur.Action == AxleActions.ToZeroFinish;
                        if (!rst)
                        {
                            return false;
                        }
                        OnToZeroComplete(ur,true);

                        msg = spLink.ReadString(240);
                        if (string.IsNullOrEmpty(msg))
                        {
                            return false;
                        }
                        ur = ProtocolV2.Unpack(msg);
                        rst = ur.Result && ur.Action == AxleActions.QueryPositionFinish;
                        if (!rst)
                        {
                            return false;
                        }
                        OnQueryPositionComplete(ur);


                        return true;
                    }
                }// link lock
            }
            return rst;
        }

        public static void OnToZeroRespond(ProtocolV2.UnpacketResult ur)
        {
            if (ur.Result
                    && ur.Action == AxleActions.ToZeroRespond
                    
                    )
            {
                if (AxleCacheManager.AxleList.ContainsKey(ur.AxleName))
                {
                    AxleCacheManager.AxleList[ur.AxleName].OtherAxleStatus = AxleActions.ToZeroRespond;
                    AxleCacheManager.AxleList[ur.AxleName].AxleStatus = AxleStatus.Running;
                }
            }

            if (!ur.Result&& AxleCacheManager.AxleList.ContainsKey(ur.AxleName))
            {
                ////stop 轴未停止，发送停止指令
                //if (ur.CommFlag == CommFunctionCode.WrongFormat.ToString())
                //{
                //    AxleManager.Stop(ur.AxleName);
                //}
                ////set status
                AxleCacheManager.AxleList[ur.AxleName].OtherAxleStatus = AxleActions.ToZeroError;
                AxleCacheManager.AxleList[ur.AxleName].AxleStatus = AxleStatus.Stoped;
            }

            setState( 
                string.Format("[{0}] 轴 归零命令响应 : {1} {2} "
                        , ur.AxleName
                        , ur.Result ? "正确" : "错误"
                        , ur.Result ? "-> 归零运行中 ... " : string.Empty
                        ));
        }

        public static void OnToZeroComplete(ProtocolV2.UnpacketResult ur)
        {
            OnToZeroComplete(ur,false);
        }
        public static void OnToZeroComplete(ProtocolV2.UnpacketResult ur,bool im)
        {
            if (ur.Result 
                && ur.Action == AxleActions.ToZeroFinish
                
                )
            {

                ParameterCacheManager.Update(ur.AxleName, Axle.Direction.ForwardDirection, double.MinValue, double.MinValue);
                if (AxleCacheManager.AxleList.ContainsKey(ur.AxleName))
                {
                    AxleCacheManager.AxleList[ur.AxleName].IsToZeroed = true;
                    AxleCacheManager.AxleList[ur.AxleName].OtherAxleStatus = AxleActions.ToZeroFinish;
                    
                    int ra = AxleCacheManager.AxleList[ur.AxleName].RunAcceleration;
                    if (ra != Axle.AccelerationLevel.Constant && ra != Axle.AccelerationLevel.Empty)
                    {
                        if (im)
                        {
                            AxleManager.AccelerationSettingIM(ur.AxleName, new Axle.AccelerationLevel(ra));
                        }
                        else
                        {
                            AxleManager.AccelerationSetting(ur.AxleName, new Axle.AccelerationLevel(ra));
                            Thread.Sleep(200);
                        }
                        //AxleManager.AccelerationSettingIM(ur.AxleName, new Axle.AccelerationLevel(ra));
                    }

                    AxleCacheManager.AxleList[ur.AxleName].RelativeZero = 0;
                    AxleCacheManager.AxleList[ur.AxleName].Position = 0;

                    AxleCacheManager.Update(ur.AxleName);
                }
                //if (im)
                //{ QueryPositionIM(ur.AxleName); }
                //else
                //{
                //    QueryPosition(ur.AxleName);
                //}
                Thread.Sleep(100);
            }
            if (!ur.Result&&AxleCacheManager.AxleList.ContainsKey(ur.AxleName))
            {
                AxleCacheManager.AxleList[ur.AxleName].OtherAxleStatus = AxleActions.ToZeroError;
            }

            AxleCacheManager.AxleList[ur.AxleName].AxleStatus = AxleStatus.Stoped;

           setState(
                string.Format("[{0}] 轴 归零命令运行结束 : {1}"
                        , ur.AxleName
                        , ur.Result ? "正确" : "错误"
                        )
                        );
        }
    }
}
